package com.oha.laporrayelchurro.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oha.laporrayelchurro.model.Pais;
import com.oha.laporrayelchurro.service.PaisService;

public class PaisServlet extends BaseServlet{

	/**
	 * serialization
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * pais Service
	 */
	private PaisService pService = new PaisService();
	
	/**
	 * accion get
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		showData(req, resp);
	}
	
	/**
	 * Accion post
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Pais pais = getPais(req);
		if(pais!=null){
			pService.saveOrUpdate(pais);
		}
		showData(req, resp);
	}
	
	/**
	 * Muestra los datos
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void showData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		List<Pais> pList = pService.getAll();
		req.setAttribute("paisList", pList);
		goToView(req, resp, "/pages/pais.jsp");
	}
	
	/**
	 * Obtiene un objeto pais desde el request
	 * @param req
	 * @return
	 */
	private Pais getPais(HttpServletRequest req){
		Pais pais = null;
		String nombre = getParam(req, "nombre");
		if(nombre!=null && nombre.trim().length()>0){
			pais=new Pais();
			pais.setNombre(nombre);
		}
		return pais;
	}

}
